package com.cxd.message.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.cxd.app.entity.base.InboxBase;
import com.cxd.app.entity.base.UserBase;
import com.cxd.app.entity.base.UserMessageTemplateBase;
import com.cxd.app.entity.base.UserMessageWayBase;
import com.cxd.base.common.constants.jdp2p.MessageConstants;
import com.cxd.base.util.BeanTools;
import com.cxd.base.util.IdGenerator;
import com.cxd.sms.service.SmsService;


@Service("messageService")
public class MessageService {

	@Resource
	public BeanTools bt;
	
	@Resource
	private SmsService smsService;
	
//	@Resource
//	private MailService  mailService;

	/**
	 * 发送消息，会根据接收用户的设定，自动判断是否发站内信、邮件、短信。
	 * 
	 * @param userId
	 *            接收用户id
	 * @param userMessageNodeId
	 *            发送消息节点id
	 * @param params
	 *            发送消息中的参数
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public void sendMsg(UserBase user, String userMessageNodeId,
			Map<String, String> params) throws InstantiationException, IllegalAccessException {
		String sql = "select umt.* from user_message um "+ 
			"right join USER_MESSAGE_TEMPLATE umt on um.MESSAGE_TEMPLATE = umt.id "+
			"inner join USER_MESSAGE_NODE umn on umt.MESSAGE_NODE = umn.id "+
			"inner join USER_MESSAGE_WAY umw on umt.MESSAGE_WAY = umw.id "+
			"where (um.user_id = '"+user.getId()+"' or umt.`status`='"+MessageConstants.UserMessageTemplateStatus.REQURIED+"') "+
			"and umt.`status` != '"+MessageConstants.UserMessageTemplateStatus.CLOSED+"'"+
			"and umn.`status` = '"+MessageConstants.UserMessageNodeStatus.OPEN+"'"+
			"and umw.`status` = '"+MessageConstants.UserMessageWayStatus.OPEN+"'"+
			"and umn.id = '"+userMessageNodeId+"'";
		List<UserMessageTemplateBase> listBean = bt.queryListBean(sql, UserMessageTemplateBase.class);
		
		for (UserMessageTemplateBase umt : listBean) {
			String msg = replaceParams(umt, params);
			UserMessageWayBase umwBean = bt.queryBean("USER_MESSAGE_WAY", "ID", umt.getMessageWay(), UserMessageWayBase.class);
			if (umwBean.getId().equals(MessageConstants.UserMessageWayId.EMAIL)) {
//				// 邮件
//				mailService.sendMail(user.getEmail(), umt.getName(), msg);
			} else if (umwBean.getId().equals(MessageConstants.UserMessageWayId.SMS)) {
				// 短信
				smsService.send(msg, user.getMobileNumber());
			} else if (umwBean.equals(MessageConstants.UserMessageWayId.LETTER)) {
				// 站内信
				sendStationMsg(user, "admin", umt.getName(), msg);
			}
		}
	}

	/**
	 * 发送邮件
	 * @param umt 发送提醒信息的模板
	 * @param params  这些参数将替换模板中的参数 如username将替换模板中的#{username}
	 * @param email  邮箱 
	 */
//	public void sendEmail(UserMessageTemplateBase umt, Map<String, String> params,
//			String email) {
//		//替换模板中的参数
//		String msg = replaceParams(umt, params);
//		//发送邮件
//		mailService.sendMail(email, umt.getName(), msg);
//	}

	public void sendSMS(UserMessageTemplateBase umt, Map<String, String> params,
			String mobileNumber) {
		String msg = replaceParams(umt, params);
		//发送短信
		smsService.send(msg, mobileNumber);
	}

	/**
	 * 替换模板里面的参数
	 * 
	 * @param umt
	 * @param params
	 * @return 替换完成的内容
	 */
	public String replaceParams(UserMessageTemplateBase umt,
			Map<String, String> params) {
		String returnStr = umt.getTemplate();
		for (String key : params.keySet()) {
			returnStr = returnStr.replace("#{" + key + "}", params.get(key));
		}
		return returnStr;
	}

	public boolean isMessageWayenable(String userMessageWayId) throws InstantiationException, IllegalAccessException {
		UserMessageWayBase umw = bt.queryBean("USER_MESSAGE_WAY", "ID", userMessageWayId, UserMessageWayBase.class);
		if (umw != null
				&& umw.getStatus().equals(
						MessageConstants.UserMessageWayStatus.OPEN)) {
			return true;
		}
		return false;
	}

	/**
	 * 根绝模板发送站内信
	 * @param umt
	 * @param params
	 * @param sender
	 * @param reveiver
	 */
	public void sendStationMsg(UserMessageTemplateBase umt,
			Map<String, String> params, UserBase sender, UserBase reveiver) {
		String msg = replaceParams(umt, params);
		sendStationMsg(reveiver, sender.getId(), umt.getName(), msg);
	}
	
	/**
	 * 发送站内信
	 * @param receiver
	 * @param sendUserId
	 * @param title
	 * @param msg
	 */
	public void sendStationMsg(UserBase receiver, String sendUserId, String title,String msg) {
		InboxBase inbox = new InboxBase();
		inbox.setId(IdGenerator.randomUUID());
		inbox.setRecevier(receiver.getId());
		inbox.setSender(sendUserId);
		inbox.setReceiveTime(new Date());
		inbox.setContent(msg);
		inbox.setStatus(MessageConstants.InBoxConstants.NOREAD);
		inbox.setTitle(title);
		bt.add(inbox);
	}
}
